package com.app.components
{
	import com.app.base.Component;
	import com.app.base.Display;
	import com.app.events.ControlEvent;
	import com.app.system.Systems;
	
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	
	public class Scroll extends Component
	{
		/** 限制水平拖动 */
		public static const HORIZONTAL:String = "horizontal";
		/** 限制垂直拖动 */
		public static const VERTICAL:String = "vertical";
		/** 任意拖动 */
		public static const ANY:String = "any";
		
		private var _type:String;
		private var _direction:int;
		
		private var _viewRect:Rectangle;
		private var _scrollRect:Rectangle;
		private var _gapH:int;
		private var _gapV:int;
		private var _mask:Sprite;
		
		/**
		 *  
		 * @param viewRect 画面大小
		 * @param scrollRect 滚动区域限制大小
		 * @param type 滚动类型，水平，垂直，任意
		 * @param gap 到达限制区域开发的间隔
		 * @param repeat 是否循环
		 * 
		 */		
		public function Scroll(viewRect:Rectangle ,scrollRect:Rectangle=null ,type:String=Scroll.ANY ,gap:int=0)
		{
			super();
			_type = type;
			_viewRect = viewRect;
			_scrollRect = scrollRect;
			_gapH = gap;
			_gapV = gap;
			
			drag = true;
			addEventListener(ControlEvent.DRAG_START ,dragHandler);
			addEventListener(ControlEvent.DRAG_STOP ,dragHandler);
			addEventListener(ControlEvent.DRAG_MOVE ,dragHandler);
			addEventListener(ControlEvent.DRAG_CAST ,dragHandler);
		}
		
		/** 拖动处理 */
		private function dragHandler(event:ControlEvent):void
		{
			switch(event.type)
			{
				case ControlEvent.DRAG_START:
					_direction = event.direction;
					return;
					
				case ControlEvent.DRAG_MOVE:
					switch(_type)
					{
						case Scroll.HORIZONTAL:
							if(_direction>=2)
							{
								move(event.endPoint.x - event.startPoint.x ,0);
								_gapV = 0;
							}
							break;
						
						case Scroll.VERTICAL:
							if(_direction<2)
							{
								move(0 ,event.endPoint.y - event.startPoint.y);
								_gapH = 0;
							}
							break;
						
						case Scroll.ANY:
							move(event.endPoint.x - event.startPoint.x ,event.endPoint.y - event.startPoint.y);
							break;
					}
					return;
					
				case ControlEvent.DRAG_STOP:
					return;
					
				case ControlEvent.DRAG_CAST:
					return;
			}
		}
		
		
		public function move(mX:Number=0 ,mY:Number=0):void
		{
			var moveX:Number = x+mX;
			var moveY:Number = y+mY;
			
			if(_scrollRect!=null && _type!=Scroll.ANY)
			{
				moveX = Math.min(Math.max(moveX ,_viewRect.width-_scrollRect.width)-_gapH ,_scrollRect.x+_gapH);
				moveY = Math.min(Math.max(moveY ,_viewRect.height-_scrollRect.height)-_gapV ,_scrollRect.y+_gapV);
			}
			
			x = moveX;
			y = moveY;
		}
	}
}